package com.wltjack.common;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Controller层异常统一处理
 */
@Slf4j
@Component
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 这里可根据不同异常引起的类做不同处理方式
        String exceptionName = ClassUtils.getShortName(ex.getClass());
        if ("NoPermissionException".equals(exceptionName)) {
            log.info("GlobalHandlerExceptionResolver > NoPermissionException ==> {}", exceptionName);
            log.info("GlobalHandlerExceptionResolver > requestUrl ==> {}", request.getRequestURL());
            ex.printStackTrace();
            // 向前台返回错误信息
            Response response1 = new Response(10000, ex.getMessage(), null);
            try {
                // 设置响应内容格式和编码方式
                request.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONObject.toJSON(response1).toString());
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
